/**
 * Created by zhagz on 2016/9/8.
 * charset:utf-8
 */

var baseUrl = "http://127.0.0.1:8080/bks_xk";

//定义几个全局变量,翻页使用
var paging_max_id = 0; //保存课程列表的max的id


$(function () {

    //得到当前用户,保存到sessionStorage中
    var getCurUser =function () {
        $.ajax({
            type: "GET",
            url: baseUrl + '/stu/curUser',
            success: function (data) {
                //加载个人信息
            	$.session.set('stu_id',JSON.stringify(data));
                getSelected(data);
            },
            error:function(data){
            	alert(data);
            }
        });
    };

    /**         运行时加载 *                                          *****/

        //在加载完页面之后加载默认全部课程

    getAllCourse(paging_max_id);

    getCurUser();
    /***********************************************************************/


    //搜索框
    $('#search_button').click(function () {
        var val = $('#search_input').val();
        var id = 0;
        if (val != '') {
            $.ajax({
                type: "POST",
                url: baseUrl + '/course/search',
                data: {key: val, id: id},
                success: function (data) {
                    deploy(data);
                },
                error: function (data) {
                    alert("无法连接服务器/course/search，请稍后刷新重试！");
                }
            });
        }
    });


    //控制筛选菜单
    $('#filter_button').click(function () {
        var course_filter_openedDep = $('#course_filter_openedDep').val();
        var course_filter_place = $('#course_filter_place').val();
        var course_filter_clazz = $('#course_filter_clazz').val();
        var course_filter_nature = $('#course_filter_nature').val();

        $.ajax({
            type: "POST",
            url: baseUrl + '/course/filte',
            data: {
                openedDep: course_filter_openedDep == 'default' ? '' : course_filter_openedDep,
                place: course_filter_place == 'default' ? '' : course_filter_place,
                clazz: course_filter_clazz == 'default' ? '' : course_filter_clazz,
                nature: course_filter_nature == 'default' ? '' : course_filter_nature
            },
            success: function (data) {
                deploy(data);
            },
            error: function (data) {
                alert("无法连接服务器/course/filte，请稍后刷新重试！");
            }
        });
    });

});
//end $.function(){};

//找到最大的id并赋值
var findMaxId = function (id) {
    paging_max_id = id > paging_max_id ? id : paging_max_id;
};

//remove 
var removeThisCourse = function (stu_id,course_id) {
    $.ajax({
        type: "POST",
        url: baseUrl + '/cs/remove',
        data: {stu_id:stu_id,course_id:course_id},
        success: function (data) {
            if(data=='success'){
                alert("删除课程成功！")
            }else{
                alert("删除课程失败！");
            }
        },
        error: function (data) {
            alert("无法连接服务器/cs/remove，请稍后刷新重试！");
        }
    });
};


//得到这个人的信息
var getSelected = function (user) {

    var user_id = user.id;

    $('#key_name').html(user.name);
    $.ajax({
        type: "POST",
        url: baseUrl + '/cs/selected',
        data: {id: user_id},
        success: function (data) {
            $('#choosed_course_list').empty();
            $('#key_courseNumber').html(data.length);
            var courseNumber = 0;
            for (var i = 0; i < data.length; i++) {
                var li = "<li><a href='/static/course.html?course_id=" + data[i].id + "'>" + data[i].name + "</a><a href='javascript:removeThisCourse("+user.id+","+data[i].id+");' class='delete_course_a' >删除</a></li>";
                $('#choosed_course_list').append(li);
                courseNumber += Number(data[i].credit);
            }
            $('#key_credit').html(courseNumber);
        },
        error: function (data) {
            alert("无法连接服务器/courseSelect/selected_briefList，请稍后刷新重试！");
        }
    });
};

//在模板添加完成后为其中的button添加监听
var addListenerInCoursePanel= function () {
    $('.course_select_button').click(function () {
        var stu = JSON.parse($.session.get('stu_id'));
        var course_id = this.value;
        $.ajax({
            type:'POST',
            url:baseUrl+'/cs/select',
            data:{stu_id:stu.id,course_id:course_id},
            success: function (data) {
                if(data=='success')alert('成功！');
                else if(data=='conflict')alert('与课程冲突！');
                else if(data=='isSelected')alert('已选择过该课程！')
                else if(data=='isFull')alert('上课人数已满！')
                else if(data=='wrongId')alert('该课程id不存在！')
                else if(data=='fullCredit')alert('可选学分已满35！')
                else alert('失败！');
            }
        });
    });

};

//负责部署data到课程列表中去,还调用了max_id方法找到maxid
//data为course对象的数组
var deploy = function (data) {
    $('#course_list_content').empty();
    if (data.length != 0 && data!=null) {
        for (var i = 0; i < data.length; i++) {
            findMaxId(data[i].id);
            $('#courseTemplate').tmpl(data[i]).appendTo('#course_list_content');
        }
        addListenerInCoursePanel();    
    } else {
            $('#course_list_content').css({
                'text-align': 'center',
                'margin': '10px auto'
            });
            $('#course_list_content').append("<span style='font-family: \"Microsoft YaHei\";font-size: 24px;'>查找不到课程！</span>");
    }
};

//得到所有课程的列表
var getAllCourse = function (id) {
    $.ajax({
        type: "POST",
        url: baseUrl + '/course/all',
        data: {id: id},
        success: function (data) {
            deploy(data);
        },
        error: function (data) {
            alert("无法连接服务器/course/all，请稍后刷新重试！");
        }
    });
};

//实现上一页下一页的功能
var paging_up_down = function (num) {
    return getAllCourse(paging_max_id + num);
};

